# encoding:utf-8
import os
from py._xmlgen import html

import pytest

LINK = True


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    当测试失败的时候，自动截图，展示到html报告中
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    try:
        page = item.module.page  # 自定义全局的page对象
    except AttributeError:
        try:
            page = item.funcargs['page']  # 内置fixture的page对象
        except KeyError:
            try:
                page = item.keywords.node.module.test.page  # 类里的setup里的page对象
            except AttributeError:
                ...
                # print("请检查：\n1.确保这是个ui自动化脚本 \n2.确保page对象处于外层或为内置对象")
                # return

    # 如果不是ui自动化，可以这是掉这个模块
    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            screen_img = capture_screenshots(file_name, page)
            if file_name:
                html = '<div><img src="%s" alt="screenshot" style="width:500px;height:270px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra

    report.description = str(item.function.__doc__)  # 描述信息为对应的函数注释
    # report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")
    # report.nodeid = report.nodeid.encode("unicode_escape").decode("utf-8")


def capture_screenshots(case_name, page):
    """
    配置用例失败截图路径
    """
    reports_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    file_name = case_name.split("/")[-1]
    # file_name = file_name.encode("utf-8").decode("unicode_escape")
    image_dir = os.path.join(reports_path, "reports", file_name)
    page.screenshot(path=image_dir)
    return file_name


def pytest_configure(config):
    """
    去掉报告中没用的环境信息
    """
    config._metadata = {}
    config._metadata['Tester'] = 'Teark'
    config._metadata["Project Name"] = "UI Autotest"


@pytest.mark.optionalhook
def pytest_html_results_summary(prefix):
    prefix.extend([html.p("Project status is good")])


@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    if LINK:
        cells.insert(1, html.th('Description'))  # 增加描述信息列
    cells.pop(-1)  # 删除link列


@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    try:
        desp = report.description
        cells.insert(1, html.td(desp))  # 描述信息行
    except AttributeError:
        global LINK
        LINK = False
    cells.pop(-1)  # 删除link列
